package cn.nbt.busManage.service.impl;

import cn.nbt.busManage.model.dto.MenuDto;
import cn.nbt.busManage.model.entity.Menu;
import cn.nbt.busManage.dao.repository.MenuRepository;
import cn.nbt.busManage.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class IMenuService implements MenuService {

    @Autowired
    private MenuRepository menuRepository;

    @Override
    public List<MenuDto> findAll() {
        List<Menu> all = menuRepository.findAll();
        if(all.isEmpty()){
            throw new RuntimeException("菜单数据为空");
        }
        ArrayList<MenuDto> menuDtos = new ArrayList<>();
        for (Menu menu : all){
            MenuDto menuDto = new MenuDto(menu);
            if(menuDto.getPid() == 0){
                ArrayList<MenuDto> menuDtos1 = new ArrayList<>();
                for (Menu menu1 : all){
                    if(menu1.getPid() == menuDto.getId()){
                        MenuDto menuDto1 = new MenuDto(menu1);
                        menuDtos1.add(menuDto1);
                    }
                }
                menuDto.setMenuDtos(menuDtos1);
                menuDtos.add(menuDto);
            }
        }
        return menuDtos;
    }

    @Override
    public MenuDto findById(Integer id) {
        Optional<Menu> menu = menuRepository.findById(id);
        if (menu.isEmpty()){
            throw new RuntimeException("该菜单不存在");
        }
        return menu.map(MenuDto::new).orElse(null);
    }

    @Override
    public List<MenuDto> findByQuery (String name) {
        List <Menu> menu = menuRepository.findByName(name);
        List<MenuDto> menuDtos = new ArrayList<>();
        for (Menu menus : menu ){
            MenuDto menuDto = new MenuDto(menus);
            menuDtos.add(menuDto);
        }
        return menuDtos;
    }

    @Override
    public void save(MenuDto menuDto) {
        Menu menu = new Menu();
        menu.setName(menuDto.getName());
        menu.setUrl(menuDto.getUrl());
        menu.setPid(menuDto.getPid());
        menuRepository.save(menu);
    }

    @Override
    public void deleteById(Integer id) {
        menuRepository.deleteById(id);
    }

    @Override
    public void update(MenuDto menuDto) {
        Menu menu = new Menu();
        menu.setId(menuDto.getId());
        menu.setName(menuDto.getName());
        menu.setUrl(menuDto.getUrl());
        menu.setPid(menuDto.getPid());
        menuRepository.save(menu);
    }
}
